package com.xvaca.spcms.servlet.receive;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.xvaca.spcms.bean.OrderBean;
import com.xvaca.spcms.bean.PipeBean;
import com.xvaca.spcms.dao.OrderDAO;
import com.xvaca.spcms.dao.PipeDAO;

/**
 * Servlet implementation class ReceiveServlet
 */
public class ReceiveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(ReceiveServlet.class);

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 获取渠道ID
		String channel = request.getPathInfo();
		if (channel == null || channel.equals("")) {
			return;
		}
		
		// 去除前面的“/”
		channel = channel.substring(1);
		int channelId = Integer.parseInt(channel);
		
		// 循环所有参数
		String params = "";
		Map<String, String[]> map = request.getParameterMap();
		Set<Entry<String,String[]>> set = map.entrySet();
		Iterator<Entry<String,String[]>> it = set.iterator();
		while (it.hasNext()) {
			Entry<String, String[]> entry= it.next();
			params = params + "&" + entry.getKey() + "=" + entry.getValue()[0];
		}
		if (params.length() > 0) params = params.substring(1); // 去除&
		
		String ip = this.getIpAddr(request);
		String reqStr = ip + " " + 
						request.getMethod() + " " + 
						channelId + " " + params;
		logger.info(reqStr);
		
		/* 获取参数 */
		String productCode = request.getParameter("productcode"); // 产品代码
		String payer = request.getParameter("payer"); // 上行手机号
		String sender = request.getParameter("sender"); // 上行长号码
		String receiver = request.getParameter("receiver"); // 上行手机号
		String linkId = request.getParameter("reserve"); // 点播-LinkID 包月-业务代码，
		String smsStatus = request.getParameter("status"); //同步状态值   0-退订, 1-包月, 2-重复订购, 3-上行, 4-扣费成功
		String cmd = request.getParameter("param"); // 上行内容  
		String moAt = request.getParameter("optime"); // 上行时间
		
		// 获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String currentTime = sdf.format(new Date());
		
		OrderDAO orderDAO = new OrderDAO();
		
		
		/** 检查记录是否已存在 */
		boolean isLinkIdExist = orderDAO.isLinkIdExist(linkId, Integer.parseInt(smsStatus));
		if (isLinkIdExist) {
			logger.info("记录已存在,无需插入,直接返回");
			return;
		}
		
		// 初始化pipeID为0
		int pipeId = 0;
		String code = "";
		
		// 判断上行还是订购
		if ("4".equals(smsStatus)) {
			// 订购，则根据linkid获取pipeid
			OrderBean order = orderDAO.getOrderByLinkid(linkId);
			if (order != null) {
				pipeId = order.getPipeId();
				code = order.getSender();
				cmd = order.getCmd();
			}
		} else {
			PipeDAO pipeDAO = new PipeDAO();
			PipeBean pipe = pipeDAO.getPipeByChannelIdAndCmd(channelId, cmd);
			if (pipe != null) {
				pipeId = pipe.getId();
				code = pipe.getChannel().getCode();
			}
		}
		
		OrderBean order = new OrderBean();
		order.setChannelId(channelId);
		order.setPipeId(pipeId);
		order.setCmd(cmd);
		order.setCreatedAt(currentTime);
		order.setLinkid(linkId);
		order.setMoAt(moAt);
		order.setPayer(payer);
		order.setProductCode(productCode);
		order.setReceiver(receiver);
		order.setSender(code); // 设置配置信息长号码
		order.setSyncSender(sender); // 设置同步过来的长号码
		order.setSmsStatus(Integer.parseInt(smsStatus));
		order.setStatus(0);
		order.setUpdatedAt(currentTime);
		order.setIp(ip);
		
		int i = orderDAO.insertOrder(order);
		// 插入记录
		logger.debug("插入记录" + i + "条");
		
		
	}
	
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
